package com.ba.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class SerializeUtil {
	static final Class<?> CLAZZ = SerializeUtil.class;
	
    public static byte[] serialize(Object value) {
        if (value == null) { 
            throw new NullPointerException("Can't serialize null");
        }
        byte[] rv = null;
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream  os = new ObjectOutputStream(bos);){
            os.writeObject(value);
            os.close();
            bos.close();
            rv = bos.toByteArray();
        } catch (Exception e) {
//        	LoggerUtils.fmtError(CLAZZ,e, "serialize error %s", JSONObject.fromObject(value));
        }
        return rv;
    }
    
	public static Object deserialize(byte[] in) {
	    Object rv = null;
        if (in != null) {
            try(ByteArrayInputStream bis = new ByteArrayInputStream(in);
                    ObjectInputStream is = new ObjectInputStream(bis);) {
                rv = is.readObject();
            } catch (Exception e) {
    //           LoggerUtils.fmtError(CLAZZ,e, "serialize error %s", in);
            }
        }
        return (Object) rv;
    }

//    public static <T> T deserialize(byte[] in, Class<T>...requiredType) {
//        Object rv = null;
//        if (in != null) {
//            try(ByteArrayInputStream bis = new ByteArrayInputStream(in);
//                    ObjectInputStream is = new ObjectInputStream(bis);) {
//                rv = is.readObject();
//            } catch (Exception e) {
//    //           LoggerUtils.fmtError(CLAZZ,e, "serialize error %s", in);
//            }
//        }
//        return (T) rv;
//    }

//    private static void close(Closeable closeable) {
	public static void close(Closeable closeable) { //这是干啥的？？
        if (closeable != null)
            try {
                closeable.close();
            } catch (IOException e) {
//            	 LoggerUtils.fmtError(CLAZZ, "close stream error");
            }
    }

}
